# -*- coding = utf-8 -*-
# @Time : 2022/10/18 10:06
# @Author :Henry L
# @File : Utils.py
# @Software : PyCharm
import ast
import base64
import os
import smtplib
from io import BytesIO
import time
# import pywinauto
from PIL import Image
import ddddocr
from email.mime.text import MIMEText
# from pywinauto import mouse, WindowSpecification
# from pywinauto import application
import psycopg2
import setting


# def change(refresh_xy, change_xy):
#     os.environ.update({"__COMPAT_LAYER": "RUnAsInvoker"})
#     app = pywinauto.Desktop()
#     if WindowSpecification.exists(app["花生代理"]):
#         dlg_spec = app["花生代理"]
#     else:
#         # 没有就创建窗口,且打开自动登录的可以使用该操作
#         application.Application(backend='uia').start(r'E:\Program Files (x86)\huashengdaili\HuaShengDaiLi.exe')
#         dlg_spec = app["花生代理"]
#     # 等到窗口真的开着
#     dlg_spec.wait('visible')
#     dlg_spec.print_control_identifiers()
#     dlg_spec.set_focus()
#     time.sleep(5)
#     mouse.click(button='left', coords=refresh_xy)
#     # mouse.click(button='left', coords=(715, 790))
#     time.sleep(5)
#     mouse.click(button='left', coords=change_xy)
#     time.sleep(5)
#     # mouse.click(button='left', coords=(850, 795))
#     time.sleep(60)
#     dlg_spec.minimize()


class Unil():
    def __init__(self):
        self.ocr = ddddocr.DdddOcr(show_ad=False)
        self.mail_host = 'smtp.qq.com'
        self.mail_user = '1161077448'
        self.mail_pass = 'qtkeskacmghqieef'
        self.receivers = ['annaliu@rektec.com.cn']
        self.sender = '1161077448@qq.com'

    def denoisy(self, name):
        """图片降噪"""
        im = Image.open(name).convert('RGB')
        pix = im.load()
        for w in range(im.size[0]):
            for h in range(im.size[1]):
                color = pix[w, h]
                if color[1] == 0 or color[1] == 43:
                    if color[0] == 255:
                        pix[w, h] = (255, 255, 255)
                    if color[0] == 204 and color[2] == 204:
                        pix[w, h] = (255, 255, 255)
                    if color[0] == 204 and color[2] == 255:
                        pix[w, h] = (255, 255, 255)
                    if color[0] == 0 and color[2] == 51:
                        pix[w, h] = (255, 255, 255)
                    if color[0] == 204 and color[2] == 153:
                        pix[w, h] = (255, 255, 255)
                else:
                    pix[w, h] = (255, 255, 255)
        im.save(name)

    def get(self, name):
        """返回验证码字符串"""
        self.denoisy(name)
        with open(name, 'rb') as check_code_byte:
            img_bytes = check_code_byte.read()
        code = self.ocr.classification(img_bytes)
        return code

    def send(self, name):
        # ipv4s = socket.gethostbyname_ex(socket.gethostname())[2]
        msg = MIMEText('您好，{} 的IP已经受限，请及时前去更换IP！'.format(name), 'plain', 'utf-8')
        msg['Subject'] = 'IP受限'
        msg['From'] = self.sender
        msg['To'] = self.receivers[0]
        try:
            smtpObj = smtplib.SMTP()
            smtpObj.connect(self.mail_host, 25)
            # 登录到服务器
            smtpObj.login(self.mail_user, self.mail_pass)
            # 发送
            smtpObj.sendmail(
                self.sender, self.receivers, msg.as_string().encode('utf-8'))
            # 退出
            smtpObj.quit()
            # print('success')
        except smtplib.SMTPException as e:
            print('error', e)

    def send_stop(self, name, num):
        msg = MIMEText('您好，{} 的 {}已经停止，请及时前去检查或更换IP！'.format(name, str(num)), 'plain', 'utf-8')
        msg['Subject'] = 'IP受限'
        msg['From'] = self.sender
        msg['To'] = self.receivers[0]
        try:
            smtpObj = smtplib.SMTP()
            smtpObj.connect(self.mail_host, 25)
            # 登录到服务器
            smtpObj.login(self.mail_user, self.mail_pass)
            # 发送
            smtpObj.sendmail(
                self.sender, self.receivers, msg.as_string().encode('utf-8'))
            # 退出
            smtpObj.quit()
        except smtplib.SMTPException as e:
            print('error', e)

    def queryDataBase(self, sql):
        conn = psycopg2.connect(
            database=setting.DATABASE, user=setting.USER, password=setting.PASSWORD, host=setting.HOST,
            port=setting.PORT
        )
        cursor = conn.cursor()
        cursor.execute(sql)
        hos_list = cursor.fetchall()
        cursor.close()
        conn.close()
        return hos_list

    def UpdateDataBase(self, sql):
        conn = psycopg2.connect(
            database=setting.DATABASE, user=setting.USER, password=setting.PASSWORD, host=setting.HOST,
            port=setting.PORT
        )
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()
        cursor.close()
        conn.close()

    def get_pic_location(self, text):
        content = ast.literal_eval(text)
        json = []
        ocr2 = ddddocr.DdddOcr(det=True, show_ad=False)
        pic = content['data']['originalImageBase64']
        keys = content['data']['wordList']
        ranges = keys[0] + keys[1] + keys[2] + keys[3]
        image_data = base64.b64decode(pic)
        image = Image.open(BytesIO(image_data))
        res = ocr2.detection(image_data)
        result = {}
        for box in res:
            x1, y1, x2, y2 = box
            boxes = [box[0] - 10, box[1] - 10, box[2] + 10, box[3] + 10]
            single = image.crop(boxes)
            self.ocr.set_ranges(ranges)
            results = self.ocr.classification(single, probability=True)
            s = ""
            p = []
            for i in results['probability']:
                p.append(max(i))
                s += results['charsets'][i.index(max(i))]
            result[s] = {"x": x1 + ((x2 - x1) // 2 + 0.5),"y": y1 + ((y2 - y1) // 2)}  # 文字位置
        for item in keys:
            if item in result.keys():
                json.append(result[item])
        return json
